import Vue from 'vue'
import {serBaseUrl} from '../../config/server.url.conf'

const downloadFile = {
    install (Vue:any) {
        Vue.prototype.downloadFile = (params:any) => {
            const xhr = new XMLHttpRequest()
            const url = serBaseUrl + `/anon/marketFileResourceApi/downloadResource?resourceId=${params.id}`
            xhr.open('GET', url, true)
            xhr.responseType = 'blob'
            // var vmThis = this
            xhr.onload = () => {
                if (xhr.status === 200) {
                    if (xhr.response && xhr.response.size && xhr.response.size > 0) {
                        const file = xhr.response
                        const fileName = params.fileName
                        if ('msSaveOrOpenBlob' in navigator) {
                            window.navigator.msSaveOrOpenBlob(file, fileName)
                        } else {
                            const fileUrl = window.URL.createObjectURL(file)
                            const a = document.createElement('a')
                            a.download = fileName
                            a.href = fileUrl
                            document.getElementsByTagName('body')[0].appendChild(a)
                            a.click()
                            const ad = a.parentNode as any
                            ad.removeChild(a)
                            window.URL.revokeObjectURL(fileUrl)
                        }
                    }
                } else {
                    //
                }
            }
            xhr.send()
        }
    }
}
Vue.use(downloadFile)
